package com.example.demo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.access.AccessDeniedHandler;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
	
	@Autowired
	private AccessDeniedHandler accessDeniedHandler;

	/*
	页面出现在这个错误its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
	.antMatchers("/webjars/**");//放开所有静态资源
	* */
	protected void configure(HttpSecurity http) throws Exception{
		http.csrf().disable()
				.authorizeRequests()
				.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
					.antMatchers("/", "/home", "/about", "/qrcode", "/qrimage","/webjars/**","/xieh/**").permitAll()
					.antMatchers("/admin/**").hasAnyRole("ADMIN")
					.antMatchers("/user/**").hasAnyRole("USER")
				     // 其他所有请求需要身份认证
					.anyRequest().authenticated()
				.and()
				.formLogin()
					.loginPage("/login")
					.permitAll()
					.and()
				.logout()
					.permitAll()
					.and()
				.exceptionHandling().accessDeniedHandler(accessDeniedHandler);
	}
	
	//create two users admin and user
	/**
	 * springboot整合security报There is no PasswordEncoder mapped for the id "null"
	 * 在Spring Security 5.0之前，默认值PasswordEncoder是NoOpPasswordEncoder需要纯文本密码。在Spring Security 5中，默认值为DelegatingPasswordEncoder，这需要密码存储格式。
	 * 在password中加入密码存储格式即可，如果是纯文本，添加{noop}即可
	 * */
	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
		auth.inMemoryAuthentication()
				.withUser("user").password("{noop}123456").roles("USER")
				.and()
				.withUser("admin").password("{noop}123456").roles("ADMIN");
	}




	
}
